package com.roy.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import javax.sound.sampled.Port;
import java.util.Scanner;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/8
 * @description:
 **/

public class ChatNettyClient {

    private int port;
    private String host;

    public ChatNettyClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void connect(){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            final ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new ChatNettyClientHandler());
                        }
                    });

            final ChannelFuture future = bootstrap.connect(host, port).sync();
            final Channel channel = future.channel();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                final String message = scanner.nextLine();
                if("q".equals(message)){
                    channel.close();
                    System.exit(0);
                }
                channel.writeAndFlush(message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 9090;
        String host = "127.0.0.1";
        final ChatNettyClient chatNettyClient = new ChatNettyClient(host, port);
        chatNettyClient.connect();
    }
}
